package com.woniu.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/ward/{wardId}")
public class WardWebSocket {
    private static final ConcurrentHashMap<String, ConcurrentHashMap<Session, String>>
            rooms = new ConcurrentHashMap<>();

    // 连接建立
    @OnOpen
    public void onOpen(Session session, @PathParam("wardId") String wardId) {
        rooms.computeIfAbsent(wardId, k -> new ConcurrentHashMap<>()).put(session, "");
    }

    // 连接关闭
    @OnClose
    public void onClose(Session session, @PathParam("wardId") String wardId) {
        rooms.getOrDefault(wardId, new ConcurrentHashMap<>()).remove(session);
    }

    // 出错
    @OnError
    public void onError(Session session, Throwable e) {
        e.printStackTrace();
    }

    // 后端主动推送
    public static void sendToWard(String wardId, String json) {
        ConcurrentHashMap<Session, String> sessions = rooms.get(wardId);
        if (sessions != null) {
            sessions.keySet().forEach(s -> {
                if (s.isOpen()) {
                    try {
                        s.getBasicRemote().sendText(json);
                    } catch (IOException ignored) {}
                }
            });
        }
    }
}
